define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'scanwork/active_report/index' + location.search,
                    detail_url: 'scanwork/active_report/detail',
                    audit_url: 'scanwork/active_report/audit',
                    batch_audit_url: 'scanwork/active_report/batchAudit',
                    del_url: 'scanwork/active_report/del',
                    multi_url: 'scanwork/active_report/multi',
                    table: 'active_report',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                sortOrder: 'desc',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {field: 'order_no', title: '订单号', formatter: function(value, row, index) {
                            return value + '<br><small class="text-muted">' + row.work_date + '</small>';
                        }},
                        {field: 'user_name', title: '员工姓名'},
                        {field: 'product_name', title: '产品', formatter: function(value, row, index) {
                            return value + ' - ' + row.model_name;
                        }},
                        {field: 'quantity', title: '生产数量', formatter: function(value, row, index) {
                            return value + ' 件';
                        }},
                        {field: 'work_hours', title: '工作时长', formatter: function(value, row, index) {
                            var html = value + ' 小时';
                            if (row.start_time && row.end_time) {
                                html += '<br><small class="text-muted">' + row.start_time + ' - ' + row.end_time + '</small>';
                            }
                            return html;
                        }},
                        {field: 'total_wage', title: '工资', formatter: function(value, row, index) {
                            return '￥' + value + '<br><small class="text-muted">计件: ￥' + row.piece_wage + ' | 计时: ￥' + row.time_wage + '</small>';
                        }},
                        {field: 'status', title: '状态', formatter: function(value, row, index) {
                            var statusMap = {
                                0: '<span class="label label-warning">待审核</span>',
                                1: '<span class="label label-success">已通过</span>',
                                2: '<span class="label label-danger">已拒绝</span>'
                            };
                            return statusMap[value] || '';
                        }},
                        {field: 'createtime', title: '创建时间', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: {
                            'click .btn-detail': function (e, value, row, index) {
                                Fast.api.open('scanwork/active_report/detail?id=' + row.id, '查看详情');
                                return false;
                            },
                            'click .btn-audit': function (e, value, row, index) {
                                Fast.api.open('scanwork/active_report/audit?id=' + row.id, '审核报工');
                                return false;
                            }
                        }, formatter: function (value, row, index) {
                            var html = '';
                            html += '<a href="javascript:;" class="btn btn-xs btn-primary btn-detail" data-id="' + row.id + '">详情</a> ';
                            if (row.status == 0) {
                                html += '<a href="javascript:;" class="btn btn-xs btn-info btn-audit" data-id="' + row.id + '">审核</a> ';
                            }
                            html += Table.api.formatter.operate.call(this, value, row, index);
                            return html;
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 监听选择变化，显示/隐藏批量审核按钮
            table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function () {
                var selectedIds = table.bootstrapTable('getSelections').map(function(item) {
                    return item.id;
                });
                
                if (selectedIds.length > 0) {
                    $('.btn-batch-audit').show();
                } else {
                    $('.btn-batch-audit').hide();
                }
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        audit: function () {
            // 图片预览功能
            $('input[name="audit_images[]"]').on('change', function() {
                var preview = $('#audit-image-preview');
                preview.empty();
                
                var files = this.files;
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    if (file.type.startsWith('image/')) {
                        var reader = new FileReader();
                        reader.onload = function(e) {
                            preview.append('<div class="col-md-4 col-sm-6 mb-3"><img src="' + e.target.result + '" class="img-responsive img-thumbnail" style="height: 120px; width: 100%; object-fit: cover;"></div>');
                        };
                        reader.readAsDataURL(file);
                    }
                }
            });
            
            // 表单提交
            $('#auditForm').on('submit', function(e) {
                e.preventDefault();
                
                console.log('=== 审核提交调试信息 ===');
                
                // 检查是否选择了审核结果
                var selectedStatus = $('input[name="status"]:checked').val();
                console.log('选择的审核状态:', selectedStatus);
                
                if (!selectedStatus) {
                    Toastr.error('请选择审核结果（通过或拒绝）');
                    return false;
                }
                
                var formData = new FormData(this);
                var btn = $(this).find('button[type=submit]');
                var originalText = btn.html();
                
                // 调试：显示表单数据
                console.log('表单数据:');
                for (var pair of formData.entries()) {
                    console.log(pair[0] + ': ' + pair[1]);
                }
                
                // 调试：显示文件信息
                var files = $('input[name="audit_images[]"]')[0].files;
                console.log('上传文件数量:', files.length);
                for (var i = 0; i < files.length; i++) {
                    console.log('文件' + i + ':', files[i].name, '大小:', files[i].size);
                }
                
                btn.html('<i class="fa fa-spinner fa-spin"></i> 提交中...').prop('disabled', true);
                
                console.log('开始发送AJAX请求...');
                
                $.ajax({
                    url: Fast.api.fixurl('scanwork/active_report/submitAudit'),
                    method: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        console.log('服务器响应成功:', response);
                        console.log('响应类型:', typeof response);
                        console.log('响应代码:', response.code);
                        console.log('响应消息:', response.msg);
                        
                        if (response.code === 1) {
                            console.log('审核成功，准备关闭弹窗');
                            Toastr.success('审核完成');
                            setTimeout(function() {
                                // 关闭弹窗并刷新父页面
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                                parent.$('#table').bootstrapTable('refresh');
                            }, 1500);
                        } else {
                            console.log('审核失败:', response.msg);
                            Toastr.error(response.msg || '审核失败');
                            btn.html(originalText).prop('disabled', false);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.log('AJAX错误详情:');
                        console.log('状态码:', xhr.status);
                        console.log('状态文本:', xhr.statusText);
                        console.log('响应文本:', xhr.responseText);
                        console.log('错误:', error);
                        
                        try {
                            var errorResponse = JSON.parse(xhr.responseText);
                            console.log('错误响应JSON:', errorResponse);
                        } catch (e) {
                            console.log('响应不是JSON格式');
                        }
                        
                        Toastr.error('网络错误，请重试');
                        btn.html(originalText).prop('disabled', false);
                    }
                });
            });
        },
        statistics: function () {
            // 检查是否加载了ECharts
            if (typeof echarts === 'undefined') {
                // 动态加载ECharts
                require(['https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js'], function() {
                    Controller.api.initStatistics();
                });
            } else {
                Controller.api.initStatistics();
            }
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            initStatistics: function () {
                // 初始化图表
                var userChart = echarts.init(document.getElementById('userChart'));
                var productChart = echarts.init(document.getElementById('productChart'));
                var statusChart = echarts.init(document.getElementById('statusChart'));
                var dateChart = echarts.init(document.getElementById('dateChart'));
                
                // 查询按钮点击事件
                $('#searchBtn').on('click', function() {
                    loadStatistics();
                });
                
                // 页面加载时执行一次查询
                loadStatistics();
                
                // 窗口大小改变时重绘图表
                $(window).on('resize', function() {
                    userChart.resize();
                    productChart.resize();
                    statusChart.resize();
                    dateChart.resize();
                });
                
                function loadStatistics() {
                    var params = {
                        start_date: $('#startDate').val(),
                        end_date: $('#endDate').val(),
                        user_id: $('#userId').val(),
                        status: $('#status').val()
                    };
                    
                    $.ajax({
                        url: Fast.api.fixurl('scanwork/active_report/statistics'),
                        method: 'GET',
                        data: params,
                        success: function(response) {
                            if (response.code === 1) {
                                updateStatistics(response.data);
                            } else {
                                Toastr.error(response.msg || '获取统计数据失败');
                            }
                        },
                        error: function() {
                            Toastr.error('网络错误，请重试');
                        }
                    });
                }
                
                function updateStatistics(data) {
                    // 更新统计卡片
                    var totalReports = 0, totalQuantity = 0, totalWage = 0;
                    
                    data.user_stats.forEach(function(item) {
                        totalReports += parseInt(item.report_count);
                        totalQuantity += parseInt(item.total_quantity);
                        totalWage += parseFloat(item.total_wage);
                    });
                    
                    $('#totalReports').text(totalReports);
                    $('#totalQuantity').text(totalQuantity);
                    $('#totalWage').text('￥' + totalWage.toFixed(2));
                    $('#avgWage').text(totalReports > 0 ? '￥' + (totalWage / totalReports).toFixed(2) : '￥0.00');
                    
                    // 更新员工统计图表
                    var userChartData = data.user_stats.map(function(item) {
                        return {
                            name: item.user_name,
                            value: parseFloat(item.total_wage)
                        };
                    });
                    
                    userChart.setOption({
                        title: { text: '员工工资统计' },
                        tooltip: { trigger: 'item' },
                        series: [{
                            type: 'pie',
                            radius: '50%',
                            data: userChartData
                        }]
                    });
                    
                    // 更新产品统计图表
                    var productChartData = data.product_stats.map(function(item) {
                        return {
                            name: item.product_name + ' - ' + item.model_name,
                            value: parseInt(item.total_quantity)
                        };
                    });
                    
                    productChart.setOption({
                        title: { text: '产品生产数量统计' },
                        tooltip: { trigger: 'item' },
                        series: [{
                            type: 'pie',
                            radius: '50%',
                            data: productChartData
                        }]
                    });
                    
                    // 更新状态统计图表
                    var statusMap = {0: '待审核', 1: '已通过', 2: '已拒绝'};
                    var statusChartData = data.status_stats.map(function(item) {
                        return {
                            name: statusMap[item.status] || '未知',
                            value: parseInt(item.count)
                        };
                    });
                    
                    statusChart.setOption({
                        title: { text: '状态分布统计' },
                        tooltip: { trigger: 'item' },
                        series: [{
                            type: 'pie',
                            radius: '50%',
                            data: statusChartData
                        }]
                    });
                    
                    // 更新日期统计图表
                    var dateLabels = data.date_stats.map(function(item) { return item.work_date; });
                    var dateValues = data.date_stats.map(function(item) { return parseInt(item.report_count); });
                    
                    dateChart.setOption({
                        title: { text: '每日报工次数统计' },
                        tooltip: { trigger: 'axis' },
                        xAxis: { type: 'category', data: dateLabels },
                        yAxis: { type: 'value' },
                        series: [{
                            type: 'line',
                            data: dateValues,
                            smooth: true
                        }]
                    });
                    
                    // 更新详细数据表格
                    updateDetailTables(data);
                }
                
                function updateDetailTables(data) {
                    // 更新用户统计表格
                    var userTableHtml = '';
                    data.user_stats.forEach(function(item) {
                        userTableHtml += '<tr>';
                        userTableHtml += '<td>' + item.user_name + '</td>';
                        userTableHtml += '<td>' + item.report_count + '</td>';
                        userTableHtml += '<td>' + item.total_quantity + '</td>';
                        userTableHtml += '<td>￥' + parseFloat(item.total_wage).toFixed(2) + '</td>';
                        userTableHtml += '<td>￥' + (parseFloat(item.total_wage) / parseInt(item.report_count)).toFixed(2) + '</td>';
                        userTableHtml += '</tr>';
                    });
                    $('#userTableBody').html(userTableHtml);
                    
                    // 更新产品统计表格
                    var productTableHtml = '';
                    data.product_stats.forEach(function(item) {
                        productTableHtml += '<tr>';
                        productTableHtml += '<td>' + item.product_name + '</td>';
                        productTableHtml += '<td>' + item.model_name + '</td>';
                        productTableHtml += '<td>' + item.report_count + '</td>';
                        productTableHtml += '<td>' + item.total_quantity + '</td>';
                        productTableHtml += '<td>￥' + parseFloat(item.total_wage).toFixed(2) + '</td>';
                        productTableHtml += '</tr>';
                    });
                    $('#productTableBody').html(productTableHtml);
                    
                    // 更新日期统计表格
                    var dateTableHtml = '';
                    data.date_stats.forEach(function(item) {
                        dateTableHtml += '<tr>';
                        dateTableHtml += '<td>' + item.work_date + '</td>';
                        dateTableHtml += '<td>' + item.report_count + '</td>';
                        dateTableHtml += '<td>' + item.total_quantity + '</td>';
                        dateTableHtml += '<td>￥' + parseFloat(item.total_wage).toFixed(2) + '</td>';
                        dateTableHtml += '</tr>';
                    });
                    $('#dateTableBody').html(dateTableHtml);
                }
            }
        }
    };
    return Controller;
}); 